import {PureComponent} from "react";
import {StoreContext} from "./StoreContext";


export default function connect(mapStateToProps,mapDispatchToProps){

    return function (WrapperComponent){


        class NewComponent extends PureComponent{

            constructor(props,context) {
                super();
                // constructor中没有 this.context，，， 环境挂载是在componentDidMount之后
                this.state = context.getState()
            }

            componentDidMount() {
                this.context.subscribe(()=>{
                    this.setState(this.context.getState())
                })
            }

            render() {
                // mapStateToProps
                var stateObj = mapStateToProps(this.context.getState());
                var dispatchObj = mapDispatchToProps(this.context.dispatch);
                return <WrapperComponent {...this.props} {...stateObj} {...dispatchObj}></WrapperComponent>
            }
        }


        NewComponent.contextType = StoreContext
        return NewComponent

    }
}


